import time
import datetime

from rest_framework import status, mixins
from rest_framework.viewsets import GenericViewSet

from common.exceptions import LogicalError
from common.pagination import PageNumberPaginationEx
from common.response import JsonResponse
from common import constants as c


# from shop import models as shop_models


class BaseReadOnlyViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet):
    """
    Base API Interface
    """
    page_size_query_param = 'size'
    pagination_class = PageNumberPaginationEx

    def get_paginated_response(self, data):
        # 分页数据展示
        return JsonResponse(code=c.API_MESSAGE_OK, message='ok', data=super().get_paginated_response(data))

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        # 不分页列表数据展示
        return JsonResponse(code=c.API_MESSAGE_OK, message='ok', data=serializer.data)

    def get_queryset(self):
        # 返回差量数据
        sync_time = self.request.GET.get('sync_time', None)
        if sync_time:
            return self.queryset.filter(sync_time__gt=sync_time, shop_license=self.request.user)
        try:
            return self.queryset.filter(shop_license=self.request.user)
        except Exception as e:
            return self.queryset.filter()

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return JsonResponse(data=serializer.data, code=c.API_MESSAGE_OK, message='ok', status=status.HTTP_200_OK)


class BaseViewSet(mixins.CreateModelMixin,
                  mixins.UpdateModelMixin,
                  mixins.DestroyModelMixin,
                  BaseReadOnlyViewSet,
                  GenericViewSet):

    def perform_update(self, serializer):
        # 更新modify_date字段
        # modify = self.request.data.get('modify_user_name', None)
        # serializer.validated_data['modify_user_name'] = modify if modify is not None else self.request.auth['name']
        super().perform_update(serializer)

    #
    def perform_create(self, serializer):
        # 创建的逻辑

        return serializer.save()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return JsonResponse(data=serializer.data, code=c.API_MESSAGE_OK, message='ok',
                            status=status.HTTP_201_CREATED,
                            headers=headers)



    #实现逻辑删除
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_deleted = c.LOG_DELETED
        instance.save()
        return JsonResponse(message='删除成功', status=status.HTTP_200_OK, code=c.API_MESSAGE_OK)




#     # 全局的创建方法
#     print(request.data)
#     pk = request.data.get('id', None)
#     instance = self.get_queryset().filter(pk=pk)
#     if instance.count():
#         # 如果主键存在，覆盖一下
#         serializer = self.get_serializer(instance[0], data=request.data, partial=True)
#         serializer.is_valid(raise_exception=True)
#         self.perform_update(serializer)
#         if getattr(instance, '_prefetched_objects_cache', None):
#             # If 'prefetch_related' has been applied to a queryset, we need to
#             # forcibly invalidate the prefetch cache on the instance.
#             instance._prefetched_objects_cache = {}
#         return JsonResponse(data=serializer.data, code=c.API_MESSAGE_OK, message='ok', status=status.HTTP_200_OK)
#     else:
#         # 如果主键不存在，直接创建
#         serializer = self.get_serializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         self.perform_create(serializer)
#         headers = self.get_success_headers(serializer.data)
#         return JsonResponse(data=serializer.data, code=c.API_MESSAGE_OK, message='ok',
#                             status=status.HTTP_201_CREATED,
#                             headers=headers)

# def update(self, request, *args, **kwargs):
#     partial = kwargs.pop('partial', False)
#     instance = self.get_object()
#     serializer = self.get_serializer(instance, data=request.data, partial=partial)
#     serializer.is_valid(raise_exception=True)
#     self.perform_update(serializer)
#
#     if getattr(instance, '_prefetched_objects_cache', None):
#         # If 'prefetch_related' has been applied to a queryset, we need to
#         # forcibly invalidate the prefetch cache on the instance.
#         instance._prefetched_objects_cache = {}
#     return JsonResponse(data=serializer.data, code=c.API_MESSAGE_OK, message='ok', status=status.HTTP_200_OK)

def destroy(self, request, *args, **kwargs):
    instance = self.get_object()
    self.perform_destroy(instance)
    return JsonResponse(code=c.API_MESSAGE_OK, message='ok', status=status.HTTP_200_OK)
